package com.xydpeng.rpc.serialize.handler;

import com.xydpeng.rpc.protocol.FastRpcProtocol;
import com.xydpeng.rpc.serialize.Serialization;
import com.xydpeng.rpc.serialize.SerializationFactory;
import com.xydpeng.rpc.serialize.SerializationType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2023/4/13
 * @description:
 */
public class SerializeHandler extends ChannelOutboundHandlerAdapter {
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof FastRpcProtocol) {
            FastRpcProtocol protocol = (FastRpcProtocol) msg;
            Object body = protocol.getBody();
            if (!(body instanceof byte[])) {
                Serialization serialization = SerializationFactory.getInstance(SerializationType.findByType(protocol.getHeader().getSerialization()));
                protocol.setBody(serialization.serialize(body));
            }
        }
        super.write(ctx, msg, promise);
    }
}
